/*
 * MsgQue.cpp
 *
 *  Created on: 2008-10-13
 *      Author: root
 */

#include "MsgQue.h"
#include <sys/ipc.h>
#include <errno.h>
#include <sys/msg.h>
#include <sys/stat.h>
#include <string.h>
#include <unistd.h>

#include <iostream>
using namespace std;

MsgQue::MsgQue(char *keywords, int mode)
{
	ownerMode = mode;
	key = ftok(keywords, 'a');
	if (mode)							// force to create
	{
		if ((queId = msgget(key, S_IRUSR | S_IWUSR | IPC_CREAT | IPC_EXCL))
				== -1)
		{
			queId = msgget(key, S_IRUSR | S_IWUSR | IPC_CREAT);
			msgctl(queId, IPC_RMID, 0);												// delete it
			queId = msgget(key, S_IRUSR | S_IWUSR | IPC_CREAT | IPC_EXCL);	//create a new one
		}
	}
	else									// return it if exist
	{
		queId = msgget(key, S_IRUSR | S_IWUSR | IPC_CREAT);
	}
//	cout << "MsgQue.cpp: " << (int)key << ":  " << (int)queId << endl;
}

MsgQue::~MsgQue()
{
	if(ownerMode)
		msgctl(queId, IPC_RMID, 0);
}

int MsgQue::send(long type, const char *msg)
{
	struct MsgType _msg;
	bzero(&_msg, sizeof(_msg));
	_msg.mtype = type;
//	_msg.msrc = 0;
	strncpy(_msg.mtext, msg, MBUFSIZ);
	msgsnd(queId, &_msg, sizeof(struct MsgType) - sizeof(long), 0);
	return 0;
}
